<?php
class com_intall
{
    public $layout = NULL;
    public $user_id = NULL;
    public function __construct()
    {
        $this->view = new system_view();
        $this->model = new model__com_model();
        $this->rt = new handle_route();
    }
    
    public function index_controller()
    {
        $html = '';
        $_seokey = $this->rt->rt_get_all_val_seo();
        $action = isset($_seokey['2'])?$_seokey['2']:'';
    
        switch($action){
            case '':
                $html = $this->list_controller();
            break;
            case 'them-moi':
                $html = $this->add_com();
            break;
            case 'chinh-sua':
                $id = isset($_seokey['3'])?$_seokey['3']:'';
                $html = $this->edit_com($id);
            break;
            case 'ajax':
                $ajax_action = isset($_seokey['3'])?$_seokey['3']:'';
                switch($ajax_action){
                    case 'updatestatus':
                        $html_ajax[] = $this->updateStatus();
                    break;
                    case 'delitem':
                        $html_ajax[] = $this->delItem();
                    break;
                }
                
            break;
        }
        
        if($action == 'ajax'){
            return $html_ajax;
        }else{
            return $html;    
        }
        
    }
    
    public function updateStatus()
    {
        $this->layout = 'ajax';
        $html = 'no-data';
        $id = isset($_POST['id'])?$_POST['id']:0;
        $status = $_POST['status'];
        if($status == 'hide'){
            $status  = 'hide';
            $title_status = 'Ẩn';
        }elseif($status == 'show')
        {
            $status = 'show';
            $title_status = 'Hiện';
        }else{
            $status = 'del';
            $title_status = 'Xóa tạm';
        }
        $data['Status'] = $status;
        $condition = $id;
        $this->model->md_cm_update_status($data, $condition);
                
        $html = $title_status;
        return $html;
    }
    
    
    public function list_controller(){
        $this->_['delAll'] = '';

        $list_com = $this->model->md_cm_list_com();
        $strHtml = $this->view->view_display('index');
        $arrHtml = $this->view->view_get_block_html($strHtml);
        
        if(!empty($list_com)){
            $strOkHtml = '';
            $status = array(
                'show'=>'Hiện',
                'hide'=>'Ẩn',
                'del'=>'Xóa tạm'
            );
            if($this->user_id == 1){
                $this->_['display'] = '';
            }else{
                $this->_['display'] = 'style="display: none;"';
            }
            
            foreach($list_com as $value){
                if($this->user_id == 1){
                    $strOkHtml .= $this->view->view_assign($arrHtml['com_all'],array(
                                                                            'com_value'                 => $value['Com'],
                                                                            'status'                    => !empty($status[$value['Status']])?$status[$value['Status']]:'Ẩn',
                                                                            'id'                        => $value['ID']
                                                                        ));
                }else{
                    $strOkHtml .= $this->view->view_assign($arrHtml['com'],array(
                                                                            'com_value'                 => $value['Com'],
                                                                            'status'                    => !empty($status[$value['Status']])?$status[$value['Status']]:'Ẩn',
                                                                            'id'                        => $value['ID']
                                                                        ));
                                                                        
                }
                
                
            }
            
            $strHtmlContent = $this->view->view_assign_block($strHtml, array('list_com'=>$strOkHtml));
            
        }else{
            $strHtmlContent = $this->view->view_assign_block($strHtml, array('list_com'=>''));
        }
        
        if($this->user_id == 1){
            $this->_['delAll'] = $arrHtml['buton_del'];
        }
        $strHtmlContent = $this->view->view_assign($strHtmlContent, $this->_);
        return $strHtmlContent;
        
    }
    
    public function add_com(){
        $seokey = $this->rt->rt_get_all_val_seo();
        $app = $seokey[0];
        $strHtml = $this->view->view_display('add');
        $arrHtml = $this->view->view_get_block_html($strHtml);
        $error = '';
        $msg = '';
        
        if(isset($_POST) && !empty($_POST['com_name'])){            
            $com_name = $_POST['com_name'];
            $msgs = $this->cteate_file_controller($com_name);
            if(!empty($msgs)){
                foreach($msgs as $msgs){
                    $msg .= $msgs;
                }
            }else{
                $_seokey = $this->rt->rt_get_all_val_seo();
                $this->model->md_cm_insert_com($com_name, $_seokey[0]);   
                $url = URL_BASE . 'installs/' . $app . '/com';
                header("Location:$url");
            }
        }
        
        $list_lang = $this->model->md_cm_get_lang();
        if(!empty($list_lang)){
            $strOkHtml = '';
            foreach($list_lang as $value){
                $strOkHtml .= $this->view->view_assign($arrHtml['input'],array(
                                                                            'lang_name'=>$value['Lang'],
                                                                            'code'=>$value['Code']
                                                                        ));
            }
        }

        
        $strHtml = $this->view->view_assign($strHtml,array('error'=>$msg));
        $strHtmlContent = $this->view->view_assign_block($strHtml, array(
                                                                        'list_input'=>$strOkHtml,
                                                                        
                                                                    ));
        return $strHtmlContent;
    }
    
    public function edit_com($id){
        $strHtml = $this->view->view_display('edit');
        $arrHtml = $this->view->view_get_block_html($strHtml);
        $error = '';
        $msg = '';
        
        $_seokey = $this->rt->rt_get_all_val_seo();
        if(!isset($_seokey[3])){
            //header("Location:" . URL_BASE);
        }
        $id = (int)$_seokey[3];
        if(empty($com_items)){
            //header("Location:" . URL_BASE);
        }

        if(isset($_POST) && !empty($_POST['id'])){
            $this->model->md_cm_update_com();
        }
        
        $list_lang = $this->model->md_cm_get_lang();
        if(!empty($list_lang)){
            $strOkHtml = '';
            foreach($list_lang as $value){
                $com_items  = $this->model->md_cm_get_com($id, $value['ID']);
                $arr_status = array('show'=>'Hiện','hide'=>'Ẩn', 'del'=>"Ẩn");
                $html_status = '';
                foreach($arr_status as $key=>$status){
                    $selected = '';
                    if($key == $com_items['Status']){
                        $selected = 'selected=""';
                    }
                    $html_status .= '<option '.$selected.' value="'.$key.'">'.$status.'</option>';
                }
                $strOkHtml .= $this->view->view_assign($arrHtml['input'],array(
                                                                            'lang_name'=>$value['Lang'],
                                                                            'code'=>$value['Code'],
                                                                            'SeoKey'=>$com_items['SeoKey'],
                                                                            'CatName'=>$com_items['CatName'],
                                                                            'ID'=>$id,
                                                                            'status_value'=>$html_status,
                                                                            'app'=>$com_items['App']
                                                                        ));
            }
        }

        
        $strHtml = $this->view->view_assign($strHtml,array('error'=>$msg));
        $strHtmlContent = $this->view->view_assign_block($strHtml, array(
                                                                        'list_input'=>$strOkHtml,
                                                                        
                                                                    ));
        return $strHtmlContent;
    }
    
    public function cteate_file_controller($com_name){
        $_seokey = $this->rt->rt_get_all_val_seo();
        $check_model = isset($_POST['model_name'])?$_POST['model_name']:'';
        $_message = array();
        $app = $_seokey['0'];
        $file_tmp = realpath('./temp/com/controller/demo.php');
        $content_source = file_get_contents($file_tmp);
        $content_source = str_replace('demo',$com_name,$content_source);
        
        /****************create file controller**************/
        $dirControler = realpath('../app/' . $_seokey['0'] . '/controller/');
        $fileController = $dirControler . '/' . $com_name .'.php';
        
        if(is_file($fileController)){
            $_message[] = 'Đã tồn tại com '. $com_name;
        }else{
            $fh = fopen($fileController, 'w+');
            fwrite($fh, $content_source);
            fclose($fh);
            
            $dirControler = realpath('../app/public/controller/');
            $fileController = $dirControler . '/' . $com_name .'.php';
            $fh = fopen($fileController, 'w+');
            fwrite($fh, $content_source);
            fclose($fh);
        }
        
        /****************create file lang*******************/
        $list_lang = $this->model->md_cm_get_lang();
        if(!empty($list_lang)){
            foreach($list_lang as $value){
                $dir_lang = realpath('../app/'.$_seokey['0'].'/view/lang/');
                $dir_lang_cur = $dir_lang . '/' . $value['DirName'];
                if(!is_dir($dir_lang_cur)){
                    mkdir($dir_lang_cur);
                }
                
                $file_lang_cur = $dir_lang_cur .'/' . $com_name . '.php';
                $file_tmp = realpath('./temp/com/view/lang/demo.php');
                $content_source = file_get_contents($file_tmp);
                
                $fh = fopen($file_lang_cur, 'w+');
                fwrite($fh, $content_source);
                fclose($fh);
                
                
                /****************create site******************************/
                $dir_lang = realpath('../app/public/view/lang/');
                $dir_lang_cur = $dir_lang . '/' . $value['DirName'];
                if(!is_dir($dir_lang_cur)){
                    mkdir($dir_lang_cur);
                }
                
                $file_lang_cur = $dir_lang_cur .'/' . $com_name . '.php';
                $fh = fopen($file_lang_cur, 'w+');
                fwrite($fh, $content_source);
                fclose($fh);
                
            }
        }
        
        /**************create file view***********************/
        $dir_view = realpath('../app/'.$_seokey['0'].'/view/temp/default/');
        $dir_view_cur = $dir_view.'/'.$com_name;
        
        $dir_view_public = realpath('../app/public/view/temp/default/');
        $dir_view_cur_public = $dir_view_public.'/'.$com_name;
        if(!is_dir($dir_view_cur)){
            mkdir($dir_view_cur);
        }
        if(!is_dir($dir_view_cur_public)){
            mkdir($dir_view_cur_public);
        }
        $view_array = array('phtml', 'js', 'css');
        foreach($view_array as $file){
            $file_tmp = realpath('./temp/com/view/temp/') . '/index.' . $file;
            $content_source = file_get_contents($file_tmp);
            $content_source = str_replace('demo',$com_name,$content_source);
            
            if($file == 'phtml')
            {
                $file_view_cur = $dir_view_cur . '/index.' . $file;
            }else{
                $file_view_cur = $dir_view_cur . '/' . $com_name . '.' . $file;
            }
            if(!file_exists($file_view_cur))
            {
                $fh = fopen($file_view_cur, 'w+');
                fwrite($fh, $content_source);
                fclose($fh);
            }
            /**********************create site**************************/
            
            $file_view_cur = $dir_view_cur_public . '/' . $com_name . '.' . $file;
            $fh = fopen($file_view_cur, 'w+');
            fwrite($fh, $content_source);
            fclose($fh);
        }
        
        /************create file model***************************/
        if($check_model != ''){
            $model_path = realpath('../') . '/app/' . $app . '/model/' . $com_name . '.php';
            $model_path_public = realpath('../') . '/app/public/model/' . $com_name . '.php';
            if(!file_exists($model_path)){
                $model_path_tmp = realpath('./temp/model/demo.php');
                $content_source = file_get_contents($model_path_tmp);
                $content_source = str_replace('demo',$com_name,$content_source);
                $fh = fopen($model_path, 'w+');
                fwrite($fh, $content_source);
                fclose($fh);
                /**********************create site**************************/
                $fh = fopen($model_path_public, 'w+');
                fwrite($fh, $content_source);
                fclose($fh);
                
            }    
        }
        
        return $_message;
    }
    
    public function delItem(){
        $id = $_POST['id'];
        $com = $_POST['com'];
        $check_del = $this->model->md_cm_check_del($id);
        if(!empty($check_del)){
            $dir_base =  realpath('.././');
            $controller_public = $dir_base . '/app/public/controller/' . $com . '.php';
            $controller_admin = $dir_base . '/app/admin/controller/' . $com . '.php';
            $model_public = $dir_base . '/app/public/model/' . $com . '.php';
            $model_admin = $dir_base . '/app/admin/model/' . $com . '.php';
            
            $view_admin = $dir_base . '/app/admin/view/temp/default/' . $com;
            $view_public = $dir_base . '/app/public/view/temp/default/' . $com;
            
            @unlink($controller_public);@unlink($controller_admin);@unlink($model_admin);@unlink($model_public);
      
            $this->delete_directory($view_admin);
            $this->delete_directory($view_public);
            
            $list_lang = $this->model->md_cm_get_lang();
            foreach($list_lang as $value){
                $lang_public = $dir_base . '/app/public/view/lang/' . $value['DirName'] . '/' . $com . '.php';
                $lang_admin = $dir_base . '/app/admin/view/lang/' . $value['DirName'] . '/' . $com . '.php';
                @unlink($lang_admin);@unlink($lang_public);
                
            }
            $this->model->md_cm_delItem($id);
        }
    }
    
    public function delete_directory($dirname) {
        $dir_handle = '';
       if (is_dir($dirname))
          $dir_handle = opendir($dirname);
       if (!$dir_handle)
          return false;
       while($file = readdir($dir_handle)) {
          if ($file != "." && $file != "..") {
             if (!is_dir($dirname."/".$file))
                @unlink($dirname."/".$file);
             else
                delete_directory($dirname.'/'.$file);    
          }
       }
       closedir($dir_handle);
       @rmdir($dirname);
       return true;
    }
    
    public function replace_string($string){
        return preg_replace('/[^a-zA-Z0-9\-]/s', '', $String);
    }
}

